import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MineFilePage extends StatefulWidget {
  @override
  _MineFilePageState createState() => _MineFilePageState();
}

class _MineFilePageState extends State<MineFilePage> {
  List userFile = new List();
  TextEditingController _mailController,
      _phoneNumberController,
      _userNameController,
      _occupationController,
      _companyController,
      _aboutController;
  bool isEdit = false;
  String sex = "";

  Future<int> getUser() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String userId = prefs.getString("userId");
      Response response = await Dio()
          .post("http://39.97.101.97:3000/user/getUser", data: {"_id": userId});
      userFile = response.data;
      _mailController = new TextEditingController(text: userFile[0]["email"]);
      _phoneNumberController = new TextEditingController(text: userFile[0]["phoneNumber"]);
      _userNameController = new TextEditingController(text: userFile[0]["userName"]);
      _occupationController = new TextEditingController(text: userFile[0]["occupation"]);
      _companyController = new TextEditingController(text: userFile[0]["company"]);
      _aboutController = new TextEditingController(text: userFile[0]["about"]);
      sex = userFile[0]["sex"];
      return 1;
    } catch (e) {
      print(e);
    }
  }

  Future<int> updateUser() async {
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String userId = prefs.getString("userId");
      Response response = await Dio().post("http://39.97.101.97:3000/user/updateUser",
          data: {
            "_id": userId,
            "email": _mailController.text,
            "phoneNumber": _phoneNumberController.text,
            "userName": _userNameController.text,
            "sex": sex.toString(),
            "occupation": _occupationController.text,
            "company": _companyController.text,
            "about": _aboutController.text,
          });
      if(response.data == 1)
        showToast("修改信息成功");
      else
        showToast("修改信息失败");
      return 1;
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUser().then((data) {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        elevation: 0,
        actions: [
          IconButton(
              icon: isEdit ? Icon(Icons.check) : Icon(Icons.edit),
              onPressed: () {
                isEdit = !isEdit;
                if(!isEdit) {
                  updateUser().then((data) {
                    getUser().then((data) {
                      setState(() {});
                    });
                  });
                } else
                  setState(() {});
              })
        ],
      ),
      backgroundColor: new Color.fromARGB(255, 242, 242, 245),
      body: new ListView(
        padding: const EdgeInsets.all(15.0),
        itemExtent: 70.0,
        children: <Widget>[
          Container(
            child: TextField(
              controller: _mailController,
              keyboardType: TextInputType.emailAddress,
              decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0)),
              ),
              enabled: isEdit,
            ),
          ),
          TextField(
            controller: _userNameController,
            keyboardType: TextInputType.name,
            decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0))),
            enabled: isEdit,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text("男"),
              Radio(
                value: "male",
                groupValue: this.sex,
                onChanged: (value) {
                  if (isEdit)
                    setState(() {
                      this.sex = value;
                    });
                },
              ),
              SizedBox(width: 50),
              Text("女"),
              Radio(
                value: "female",
                groupValue: this.sex,
                onChanged: (value) {
                  if (isEdit)
                    setState(() {
                      this.sex = value;
                    });
                },
              )
            ],
          ),
          TextField(
            controller: _phoneNumberController,
            keyboardType: TextInputType.phone,
            decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0))),
            enabled: isEdit,
          ),
          TextField(
            controller: _occupationController,
            keyboardType: TextInputType.text,
            decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0))),
            enabled: isEdit,
          ),
          TextField(
            controller: _companyController,
            keyboardType: TextInputType.text,
            decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0))),
            enabled: isEdit,
          ),
          TextField(
            controller: _aboutController,
            keyboardType: TextInputType.text,
            maxLines: 3,
            decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(32.0))),
            enabled: isEdit,
          ),
        ],
      ),
    );
  }
}
